<template>
  <el-container v-loading="loading" v-show="!hasScholar">
    <el-main>
      <div class="no-scholar-portal">
        <el-empty description="当前学者无门户"></el-empty>
      </div>
    </el-main>
  </el-container>
  <el-container v-loading="this.loading" v-show="hasScholar">
      <el-aside width="700px">
          <el-header height="260px">
              <el-card shadow="hover" style="margin-top: 30px;">
                  <template #header>
                      <el-row>
                          <el-col :span="4">
                              <el-avatar :src="circleUrl" :size="70" />
                          </el-col>
                          <el-col :span="10">
                              <strong class="scholar-name">{{ this.scholar.display_name }}</strong>
                          </el-col>
                          <el-col :span="5">
                              <!-- <el-button v-show="!FollowState" type="primary" class="button-name"
                                  @click="FollowAdd">关注学者</el-button>
                              <el-button v-show="FollowState" type="warning" class="button-name"
                                  @click="FollowRemove">取消关注</el-button> -->
                                  <el-button
                                      :type="followState"
                                      class="button-name"
                                      @click="toggleFollow"
                                      >
                                      {{ followAction }}
                                      </el-button>
                          </el-col>
                          <el-col :span="5">
                              <el-button v-show="!hasClaimed" type="info" class="button-name"
                                  @click="this.Claim.ClaimDialog = true">认领门户</el-button>
                              <el-button v-show="hasClaimed" type="warning" class="button-name" disabled>门户已认领</el-button>
                          </el-col>
                      </el-row>
                  </template>
                  <div>
                      <el-row style="margin-top: 4%;" v-if="this.scholar.last_known_institution != null">
                          <span class="gutter">学者机构:</span>
                          <el-button link class="gutter" type="primary" @click="gotoIns">{{
                              this.scholar.last_known_institution.display_name
                          }}</el-button>
                          <el-tag size="large" effect="light" round class="gutter" type="success">{{
                              this.scholar.last_known_institution.country_code
                          }}</el-tag>
                          <el-tag size="large" effect="light" round class="gutter" type="success">{{
                              this.scholar.last_known_institution.type }}</el-tag>
                      </el-row>
                      <el-row>
                          <span class="gutter">文献总数：{{ this.scholar.works_count }}</span>
                          <span class="gutter">文献总被引数：{{ this.scholar.cited_by_count }}</span>
                      </el-row>
                  </div>
              </el-card>
          </el-header>
          <el-main style="margin-top: 40px;">
              <el-card shadow="hover">
                <template #header>
                    <div class="card-header">
                    <span>学者简介</span>
                    </div>
                </template>
                <div style="height: 200px;">
                  <p v-if="hasClaimed">{{ description }}</p>
                  <p v-else style="color:rgb(112, 113, 113)">暂无简介</p>
                </div>
              </el-card>
          </el-main>
          <el-main style="margin-top: 40px;height: 529px;">
                  <div style="margin-left: 20%;margin-top:0%;margin-bottom: 10%;">
                      <tagcloud :tags="this.tags" width="325" height="325" radius="150"></tagcloud>
                  </div>
          </el-main>
      </el-aside>
      <el-main>
          <el-main>
              <el-card shadow="hover">
                  <div id="charts" style="width: 750px;height: 600px;" v-if="scholar.counts_by_year && scholar.counts_by_year.length !== 0">
                  </div>
                  <el-empty description="该学者暂无数据" v-else></el-empty>
              </el-card>
          </el-main>
          <el-main v-show="!isStatic">
            <el-card shadow="hover">
                <el-row>
                <el-space direction="vertical" wrap>
                    <el-table :data="this.results" style="width: 100%;" class="table" @row-click="gotoWork">
                    <el-table-column prop="title" label="文献名称" width="710" show-overflow-tooltip />
                    </el-table>
                </el-space>
                </el-row>
                <el-row>
                <el-pagination v-model:current-page="curpage" :page-size="10" :pager-count="11" layout="prev, pager, next"
                    :total="this.scholar.works_count" hide-on-single-page="true" background />
                </el-row>
            </el-card>
          </el-main>
      </el-main>
  </el-container>
  <el-dialog v-model="Claim.ClaimDialog" title="门户认领申请" width="40%">
      <span>请上传门户认领所需的相关身份信息</span>
      <el-input v-model="this.Claim.introduction" :autosize="{ minRows: 4, maxRows: 6 }" type="textarea"
          placeholder="请输入介绍" style="margin-top:20px;" />
      <div style="margin-top: 20px;">
          <el-upload action="#" list-type="picture-card" :auto-upload="false" v-model:file-list="this.Claim.pictures"
              :before-close="CancelClaim" :limit="1">
              <el-icon>
                  <Plus />
              </el-icon>
              <template #file="{ file }">
                  <div>
                      <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                      <span class="el-upload-list__item-actions">
                          <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                              <el-icon><zoom-in /></el-icon>
                          </span>
                          <span class="el-upload-list__item-delete" @click="PictureRemove(file)">
                              <el-icon>
                                  <Delete />
                              </el-icon>
                          </span>
                      </span>
                  </div>
              </template>
          </el-upload>
      </div>
      <template #footer>
          <span class="dialog-footer">
              <el-button @click="CancelClaim">取消门户认领</el-button>
              <el-button type="primary" @click="getBlob()">
                  申请门户
              </el-button>
          </span>
      </template>
  </el-dialog>
  <el-dialog v-model="PreviewDialog">
      <img :src="PreviewImageUrl" alt="Preview Image" width="815" />
  </el-dialog>
</template>

<script>
import { UserFilled } from '@element-plus/icons-vue'
import tagcloud from '/src/components/tagcloud.vue'
import {
  req_starScholarAdd,
  req_starScholarAsk,
  req_starScholarRemove,
  req_Scholar,
  req_claim,
  req_scholarToWork,
  req_getPortalInfo
} from '/src/api'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
export default {
  name: "ScholarView",
  data() {
      return {
          circleUrl: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
          scholar: {},
          curpage: 1,
          scholar_id: this.$route.params.scholar_id,
          tags: [],
          results: [],
          totalresults: [],
          Claim: {
              ClaimDialog: false,
              pictures: [],
              introduction: "",
          },
          PreviewDialog: false,
          PreviewImageUrl: '',
          FollowState: 1,
          loading: true,
          followAction: "关注学者",
          followState: "primary",
          hasScholar:true,
          description: '',
          hasClaimed: false
      };
  },
  methods: {
      async FollowAdd() {
          await req_starScholarAdd(this.scholar_id).then((response) => {
              ElMessage.success("关注成功！")
              this.FollowState = 1
          })
      },
      async FollowRemove() {
          await req_starScholarRemove(this.scholar_id).then((response) => {
              ElMessage.success("取消关注成功！")
              // console.log("取消");
              this.FollowState = 0
          })
      },
      toggleFollow() {
          if(!this.isFollowed){
              this.FollowAdd();
              this.isFollowed = 1;
              this.followAction = "取消关注";
              this.followState = "warning";
          }
          else{
              this.FollowRemove();
              this.isFollowed = 0;
              this.followAction = "关注学者";
              this.followState = "primary";
          }

      },
      gotoWork(row, column, event) {
          //ElMessage.success(row.title)
          let routeUrl = this.$router.resolve({
              path: '/paper/' + row.id
          });
          window.open(routeUrl.href, '_blank');
      },
      gotoIns() {
          let routeUrl = this.$router.resolve({
              path: '/org/' + this.scholar.last_known_institution.id
          });
          window.open(routeUrl.href, '_blank');
          //ElMessage.success(this.scholar.last_known_institution.display_name)
      },
      GotoScholar() {
          let routeUrl = this.$router.resolve({
              path:'/scholar/' + this.scholar_id
          });
          window.open(routeUrl.href, '_blank');
      },
      setTags() {
          this.scholar.x_concepts.forEach((element) => {
            // console.log("tags: ",this.tags)
              this.tags.push({ name: element.display_name, id: element.id })
          });
      },
      CancelClaim() {
          this.Claim.ClaimDialog = false
      },
      async ContinClaim(res, url) {
          const responsewe = await fetch(url)
          const blob = await responsewe.blob()

          this.Claim.ClaimDialog = false
          let Form = new FormData()
          Form.append('file', blob, this.Claim.pictures[0].name);
          Form.append('scholar_id', this.scholar_id)
          Form.append('introduction', this.Claim.introduction)
          let response = await req_claim(Form)
          if (response.data.errno === 1) {
              ElMessage.success("申请门户成功")
          }
          else {
              ElMessage.error(response.data.msg)
          }
          this.Claim.pictures = []
      },
      arrayBufferToBase64(buffer) {
          let binary = '';
          let bytes = new Uint8Array(buffer);
          let len = bytes.byteLength;
          for (let i = 0; i < len; i++) {
              binary += String.fromCharCode(bytes[i]);
          }
          return window.btoa(binary);
      },
      async getBlob() {
          if (this.Claim.pictures.length == 0) {
              ElMessage.error("请输入至少一张图片！")
          }
          else {
              let reader = new FileReader()
              reader.onload = (e) => {
                  this.ContinClaim(this.arrayBufferToBase64(e.target.result), url)
              }
              let url = this.Claim.pictures[0].url
              await fetch(url)
                  .then((response) => {
                      return response.blob()
                      // 转为文件流 请求类型类型 或其他类型
                  })
                  .then(res => {
                      reader.readAsArrayBuffer(res)
                  })
          }
      },
      async Init() {
          await req_Scholar(this.scholar_id).then(async (response) => {
              this.scholar = response.data.scholar
              if(response.data['errno'] === 2002){
                this.loading = false
                this.hasScholar = false
                // console.log(response.data.errno)
                ElMessage.info("当前学者无门户")
                // this.$router.push("/home")
                
                
              }else if(response.data['errno'] === 1){
                this.hasScholar = true;
                // ElMessage.info("当前学者有门户")
                await req_scholarToWork(this.scholar_id).then(async (response) => {
                  this.scholar.works_count = response.data.results.length
                  // console.log(response.data.msg)
                  // console.log("sch3",this.scholar)

                  await req_starScholarAsk(this.scholar_id).then(async (response) => {
                      this.FollowState = response.data.result
                      this.setTags()
                      this.loading = false
                  })
                  this.totalresults = response.data.results
                  this.results = this.totalresults.slice(0, 10)
              })
              } 
          })
          if(this.FollowState){
              this.followState = "warning";
              this.followAction = "取消关注";
          }
          else{
              this.followState = "primary";
              this.followAction = "关注学者";
          }

          await req_getPortalInfo(this.scholar_id).then((response) => {
              this.description = response.data.introduction;
              this.hasClaimed = response.data.claimed;
          })
      },
      PictureRemove(file) {
          this.Claim.pictures = this.Claim.pictures.filter(function (param) {
              return !(param.url === file.url)
          })
      },
      handlePictureCardPreview(file) {
          this.PreviewImageUrl = file.url
          this.PreviewDialog = true
      },
      setStatic() {
          let myChart = echarts.init(document.getElementById('charts'))
          myChart.setOption({
              color: ['#5470C6', '#EE6666'],
              tooltip: {
                  trigger: 'none',
                  axisPointer: {
                      type: 'cross',
                      snap: true,
                  }
              },
              legend: {},
              grid: {
                  top: 70,
                  bottom: 50
              },
              xAxis: [
                  {
                      type: 'category',
                      axisTick: {
                          alignWithLabel: true
                      },
                      axisLine: {
                          onZero: false,
                          lineStyle: {
                              color: '#EE6666'
                          }
                      },
                      axisPointer: {
                          label: {
                              formatter: function (params) {
                                  return (
                                      '年份  ' +
                                      params.value +
                                      (params.seriesData.length ? '：' + '作品数：' + params.seriesData[0].data + '   引用数： ' + params.seriesData[1].data : '')
                                  );
                              }
                          }
                      },
                      // prettier-ignore
                      data: this.scholar.counts_by_year.map(item => item.year).reverse()
                  }
              ],
              yAxis: [
                  {
                      type: 'value',
                      position: 'left',
                      name: '年作品数'
                  },
                  {
                      type: 'value',
                      position: 'right',
                      name: '年作品引用数'
                  }
              ],
              series: [
                  {
                      name: '年作品数',
                      type: 'line',
                      yAxisIndex: 0,
                      smooth: true,
                      emphasis: {
                          focus: 'series'
                      },
                      data: this.scholar.counts_by_year.map(item => item.works_count).reverse()
                  },
                  {
                      name: '年作品引用数',
                      type: 'line',
                      smooth: true,
                      emphasis: {
                          focus: 'series'
                      },
                      yAxisIndex: 1,
                      data: this.scholar.counts_by_year.map(item => item.cited_by_count).reverse()
                  }
              ]
          })
      }
  },
  watch: {
      "Claim.ClaimDialog"(newVal, oldVal) {
          setTimeout(() => {
              this.Claim.pictures = []
              this.Claim.introduction = ""
          }, 1000);
      },
      curpage(newVal, oldVal) {
      this.results = this.totalresults.slice((newVal - 1) * 10, newVal * 10)
      }
  },
  created() {
    //   this.Init()
      
    //     console.log("sch2",this.scholar);  
  },
  async mounted() {
    await this.Init();    
      if (this.scholar.counts_by_year.length && this.hasScholar) {
          this.setStatic()
      }
  }
}
</script>

<style scoped>
.gutter {
  font-size: large;
  margin-right: 2%;
}

.title-first-item {
  font-size: 20px;
  margin-right: 400px;
  width: 200px;
}

.title-second-item {
  font-size: 20px;

}

.el-row {
  margin-bottom: 20px;
}

.scholar-name {
  font-size: 20px;
  color: black;
  font-family: Arial;
  position: absolute;
  top: 30%;
}

.button-name {
  position: absolute;
  top: 30%;
}

:deep(.el-table tr) {
  background-color: white;
  height: 50px;
}

:deep(.el-table th) {
  background-color: white;
  font-size: 24px;
}

:deep(.el-table) {
  width: 100%;
  font-size: 18px;
  background-color: white;
}

.table{
  cursor: pointer;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.no-scholar-portal {
  text-align: center;
  padding: 20px;
  font-size: 18px;
  color: #999;
}
</style>
  